Java 串流是個資料序列,他不會儲存資料或是修改原始的來源。可支援泛函程式設計,通持會由某個資料來源產生串流,透過一系列的中間操作(稱作 管道 (pipelin))來傳遞資料,最後會接上一個最終表達式來表示結果。
建立串流有幾種方式:
Stream.of(T... values)
與 Stream.of(T t)
方法創建String names = Stream.of("Gomez", "Morticia", "Wednesday", "Pugsley")
.collect(Collectors.joining(","));
System.out.println(names);
String[] munsters = {"Herman", "Lily", "Eddie", "Marilyn", "Grandpa"};
names = Arrays.stream(munsters)
.collect(Collectors.joining(","));
List<LocalDate> days = Stream.iterate(LocalDate.now(), ld -> ld.plusDays(1L))
.limit(10)
.collect(Collectors.toList());
System.out.println(days);
DoubleSummaryStatistics stats = DoubleStream.generate(Math::random)
.limit(1_000_000)
.summaryStatistics();
System.out.println(stats);
//output: DoubleSummaryStatistics{count=1000000, sum=499938.617059, min=0.000001, average=0.499939, max=0.999999}
List<String> bradyBunch = Arrays.asList("Greg", "Marcia", "Peter", "Jan", "Bobby", "Cindy");
names = bradyBunch.stream().collect(Collectors.joining(","));
System.out.println(names);
System.out.println("Using IntStream.range() & IntStream.rangeClosed()");
IntStream.range(1, 10).forEach(i -> System.out.print(i + " "));
System.out.println();
IntStream.rangeClosed(1, 10).forEach(i -> System.out.print(i + " "));
//cannot compiled
//IntStream.of(1,2,3,4,5).collect(Collectors.toList());
List<Integer> ints = IntStream.of(1,2,3,4,5)
.boxed()
.collect(Collectors.toList());
Java 泛函模式通常使用一種所謂的 map, filter, reduce 的處理方式
map - 串流轉換型態成另一個串流
filter - 過濾條件
reduce - 最終操作產生一個值
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
int result = numbers
.stream()
.reduce(0, (subtotal, element) -> subtotal + element);
assertThat(result).isEqualTo(21);
List<String> strings = Arrays.asList("this", "is", "a", "list", "of", "strings");
List<String> sorted = strings.stream()
.sorted(Comparator.comparingInt(String::length))
.collect(Collectors.toList());
string.stream()
.reduce((prev, curr) -> {
assertTrue(prev.length() <= curr.length());
return curr;
});
現代 Java - 輕鬆解決 Java 8 與 的難題(O'REILLY)